﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http.Controllers;

namespace API.Core.AuthorizeAttribute
{
    public class SimpleEdexAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
    {
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (!Authenticate(actionContext))
                HandleUnauthorizedRequest(actionContext);
        }


        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            base.HandleUnauthorizedRequest(actionContext);

            var response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
            response.Content = new System.Net.Http.StringContent("Api key is not valid");
            actionContext.Response = response;
        }


        private bool Authenticate(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            var api_key = System.Web.HttpContext.Current.Request["api_key"];

            if (String.IsNullOrEmpty(api_key))
                return false;

            var sessionRepository = new API.Models.Repository.SEC_SESSIONS_Repository();
            var session = sessionRepository.GetSession(api_key);

            if (session == null)
                return false;

            actionContext.ControllerContext.RouteData.Values["session"] = session;
            actionContext.ActionArguments.Add("api_key", api_key);

            return true;
        }
    }
}